<?php

// PDO对象
if( isset($GLOBALS['config']['database']['database']) && $GLOBALS['config']['database']['database']!=''){
    $dsn="{$GLOBALS['config']['database']['type']}:host={$GLOBALS['config']['database']['hostname']};port={$GLOBALS['config']['database']['hostport']};dbname={$GLOBALS['config']['database']['database']};charset={$GLOBALS['config']['database']['charset']}";
	try {
		$GLOBALS["db"] = new PDO($dsn,$GLOBALS['config']['database']['username'],$GLOBALS['config']['database']['password']);
	}catch (PDOException $e){	 
		exit('数据库服务器连接失败！或数据库不存在或不可用！<br />'.'Error!: ' . $e->getMessage() . '<br/>');
	}
}else{
	//exit('数据库配置文件未配置！<br/>');
	if(  ( isset($_REQUEST[ $GLOBALS['config']['var_pathinfo'] ]) && (strpos( $_REQUEST[ $GLOBALS['config']['var_pathinfo'] ],'install' ) !==0) )   ){
		header('location:' . url(['install','index','index']) ); // 安装路径
		exit();
	}
}

// 初始化配置
if(isset($GLOBALS['db']) ){
    $sql="select * from ".tablename('sys_config') ;
    $rs=$GLOBALS['db']->query($sql);
    foreach($rs as $row){
        //$arr[$row['name'] ] = json_decode( $row['value'] , true );
        $GLOBALS['config'][ $row['name'] ] = json_decode( $row['value'] , true );
    }

    //$GLOBALS['config']['config']= $arr;
}

//////////////////////////////////////////

// 添加数据
if (!function_exists('pdo_insert')) {
    function pdo_insert($tablename,$data){
        //获取字段数量
		$fields = [];
        $pre=[];
        foreach( $data  as $k =>$v ){
			$fields[]= "`$k`";
            $pre[]= '?';
        }
		$fields = implode(',',$fields);
		$pre = implode(',',$pre);

        //执行sql
        $sql=" INSERT INTO ".tablename($tablename)." ( $fields )VALUES( $pre )";
        $statement = $GLOBALS['db']->prepare($sql);
        $ok=$statement->execute(array_values($data));
        if($ok){
            if($GLOBALS['db']->lastInsertId()){
				$result=$GLOBALS['db']->lastInsertId();
			}else{
				$result=true;
			}
        }else{
            $result=0;
        }
        return $result;
    }
}

// 修改数据
if (!function_exists('pdo_update')) {
    function pdo_update($tablename,$data,$where){
        $field='';
        $where_field='';
        //修改字段
        foreach($data as $key => $val){
            $field .= "`$key` =?,";
        }
        //条件字段
        foreach($where as $key =>$val){
            $where_field .= "`$key` =? and ";
        }
        $field=substr($field,0,strlen($field)-1);
        $where_field=substr( $where_field,0 , strlen($where_field)-5 );

        //执行sql
        $sql=" UPDATE ".tablename($tablename)." SET $field WHERE $where_field ";
        $statement = $GLOBALS['db']->prepare($sql);
        $ok=$statement->execute( array_merge(array_values($data),array_values($where) ) );
        if($ok){
            $result=true;
        }else{
            $result=false;
        }
        return $result;
    }
}

// 查询数据 单条
if (!function_exists('pdo_fetch')) {
    function pdo_fetch( $sql,$params = [] ){
        //$result=$GLOBALS['db']->query($sql)->fetch(\PDO::FETCH_ASSOC);
		$statement = $GLOBALS['db']->prepare($sql);
		$result = $statement->execute($params);	
		
		if (!$result) {
			$result = false;
		} else {
			$result = $statement->fetch(\PDO::FETCH_ASSOC);
		}
		
        return $result;
    }
}


// 查询数据 多条
if (!function_exists('pdo_fetchall')) {
    function pdo_fetchall( $sql,$params = [] ){
        //$result=$GLOBALS['db']->query($sql)->fetchall(\PDO::FETCH_ASSOC);
		$statement = $GLOBALS['db']->prepare($sql);
		$result = $statement->execute($params);	
		
		if (!$result) {
			$result = false;
		} else {
			$result = $statement->fetchAll(\PDO::FETCH_ASSOC);
		}
		
        return $result;
    }
}
